package com.caus.activities;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpOptions;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Environment;

import com.caus.entities.Notificacion;
import com.caus.entities.Oficina;
import com.caus.entities.User;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;

	public class AsyncConnection extends AsyncTask{
    
	protected void onProgressUpdate(Integer... progress) {
        
    }

    protected void onPostExecute(Long result) {
        
    }
    public void retrieveImage(Object...params){
		HttpClient client = new DefaultHttpClient();
		
		String url = (String)params[0];
		String id = (String)params[1];	
		//HttpGet httpGetParam   =   new HttpGet(url);
		HttpGet httpGet   =   new HttpGet(url+id);
		BufferedInputStream bis=null;
		
		HttpResponse response = null;
		try {
			response = client.execute(httpGet);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		StatusLine statusLine = response.getStatusLine();
		int statusCode = statusLine.getStatusCode();
		
		if (statusCode == 200) { //result OK
			HttpEntity entity = response.getEntity();
			InputStream content = null;
			try {
				content = entity.getContent();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			BufferedReader reader = new BufferedReader(new InputStreamReader(content));
			//nuevo
			byte[] buffer = new byte[1024];
			int i = -1;
			 bis = new BufferedInputStream(content);
			//return  bis;
			File sdCard = Environment.getExternalStorageDirectory();
			File dir = new File (sdCard.getAbsolutePath() + "/imagenesOrt/"+id+".jpg");
			FileOutputStream fos = null;
			try {
				fos = new FileOutputStream(dir);
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			}
			try {
				while((i = bis.read(buffer)) != -1) {
					fos.write(buffer, 0, i);
				}
				fos.flush();
				fos.close();
				bis.close();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
    	
    	
    }
		
	public User retrieveUser(Object... params) {
		StringBuilder builder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		
		String url = (String)params[0];
		String id = (String)params[1];
		
		//HttpGet httpGetParam   =   new HttpGet(url);
		
		//HttpGet httpGet   =   new HttpGet("http://192.168.1.104:8080/SpringServiceSample/service/greeting/user/"+id);
		HttpGet httpGet   =   new HttpGet(url+id);
		BufferedInputStream bis = null;
		
		HttpResponse response = null;
		try {
			response = client.execute(httpGet);
		} catch (ClientProtocolException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		StatusLine statusLine = response.getStatusLine();
		int statusCode = statusLine.getStatusCode();
		
		if (statusCode == 200) { //result OK
			HttpEntity entity = response.getEntity();
			InputStream content = null;
			try {
				content = entity.getContent();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(content));
		
		String line;
		try {
			while ((line = reader.readLine()) != null) {
				builder.append(line);
			}
		} catch (IOException e) {
				e.printStackTrace();
			}
		} 
		else { //result BAD
		System.err.println("Failed to download file");
		}
		
		//resultado JSON
		String jsonFeed = builder.toString();
		User user =null;
		
		//creamos objeto JSON
		JSONObject jsonObject =null;
		try {
			jsonObject = new JSONObject(jsonFeed);
			ObjectMapper mapper = new ObjectMapper();
			user = mapper.readValue(builder.toString(), User.class);
			String firstName=user.getFirstName();
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return user;
		}
	
	
	public List<User> retrieveAllUsers(Object... params) {
		StringBuilder builder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		List<User>  users =new ArrayList() ;
		
		String url = (String)params[0];
		String codigo = (String)params[1];
		String  urlhttp = url+codigo;
		//HttpGet httpGetParam   =   new HttpGet(url);
		
		HttpGet httpGet   =   new HttpGet(urlhttp);
		HttpResponse response = null;
		try {
			response = client.execute(httpGet);
		} catch (ClientProtocolException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		StatusLine statusLine = response.getStatusLine();
		int statusCode = statusLine.getStatusCode();
		
 		if (statusCode == 200) { //result OK
			HttpEntity entity = response.getEntity();
			InputStream content = null;
			try {
				content = entity.getContent();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(content));
		
		String line;
		try {
			while ((line = reader.readLine()) != null) {
				builder.append(line);
			}
		} catch (IOException e) {
				e.printStackTrace();
			}
		} 
		else { //result BAD
		System.err.println("Failed to download file");
		}
		
		//resultado JSON
		String jsonFeed = builder.toString();
		
		
		//creamos objeto JSON
		JSONArray jsonArray =null;
		try {
			//jsonArray = new JSONArray(jsonFeed);
		
			ObjectMapper mapper = new ObjectMapper();
			users = mapper.readValue(builder.toString(), new TypeReference<List<User>>() {});
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return users;
		}
	
	
	
	public Oficina retrieveOfficeById(Object... params) {
		StringBuilder builder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		Oficina oficina = new Oficina();

		String url = (String) params[0];
		String officeId = (String) params[1];
		String urlhttp = url + officeId;
		// HttpGet httpGetParam = new HttpGet(url);

		HttpGet httpGet = new HttpGet(urlhttp);
		HttpResponse response = null;
		try {
			response = client.execute(httpGet);
		} catch (ClientProtocolException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		StatusLine statusLine = response.getStatusLine();
		int statusCode = statusLine.getStatusCode();

		if (statusCode == 200) { // result OK
			HttpEntity entity = response.getEntity();
			InputStream content = null;
			try {
				content = entity.getContent();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					content));

			String line;
			try {
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else { // result BAD
			System.err.println("Failed to download file");
		}

		// resultado JSON
		String jsonFeed = builder.toString();

		// creamos objeto JSON
		JSONArray jsonArray = null;
		try {
			// jsonArray = new JSONArray(jsonFeed);

			ObjectMapper mapper = new ObjectMapper();
			oficina = mapper.readValue(builder.toString(), Oficina.class);
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return oficina;
	}
	
	
	public List<User> retrieveFuncListByOffice(Object... params) {
		StringBuilder builder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		List<User>  users =new ArrayList() ;
		
		String url = (String)params[0];
		String officeId = (String)params[1];
		String  urlhttp = url+officeId;
		//HttpGet httpGetParam   =   new HttpGet(url);
		
		HttpGet httpGet   =   new HttpGet(urlhttp);
		HttpResponse response = null;
		try {
			response = client.execute(httpGet);
		} catch (ClientProtocolException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		StatusLine statusLine = response.getStatusLine();
		int statusCode = statusLine.getStatusCode();
		
 		if (statusCode == 200) { //result OK
			HttpEntity entity = response.getEntity();
			InputStream content = null;
			try {
				content = entity.getContent();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(content));
		
		String line;
		try {
			while ((line = reader.readLine()) != null) {
				builder.append(line);
			}
		} catch (IOException e) {
				e.printStackTrace();
			}
		} 
		else { //result BAD
		System.err.println("Failed to download file");
		}
		
		//resultado JSON
		String jsonFeed = builder.toString();
		
		
		//creamos objeto JSON
		JSONArray jsonArray =null;
		try {
			//jsonArray = new JSONArray(jsonFeed);
		
			ObjectMapper mapper = new ObjectMapper();
			users = mapper.readValue(builder.toString(), new TypeReference<List<User>>() {});
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return users;
		}
	
	public List<Oficina> retrieveAllOffices(Object... params) {
		StringBuilder builder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		List<Oficina>  offices =new ArrayList() ;
		
		String url = (String)params[0];
		HttpGet httpGet   =   new HttpGet(url);
		HttpResponse response = null;
	
		try {
			response = client.execute(httpGet);
		} catch (ClientProtocolException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		StatusLine statusLine = response.getStatusLine();
		int statusCode = statusLine.getStatusCode();
		
		if (statusCode == 200) { //result OK
			HttpEntity entity = response.getEntity();
			InputStream content = null;
			try {
				content = entity.getContent();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(content));
		
		String line;
		try {
			while ((line = reader.readLine()) != null) {
				builder.append(line);
			}
		} catch (IOException e) {
				e.printStackTrace();
			}
		} 
		else { //result BAD
		System.err.println("Failed to download file");
		}
		
		try {
			ObjectMapper mapper = new ObjectMapper();
			offices = mapper.readValue(builder.toString(), new TypeReference<List<Oficina>>() {});
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return offices;
		}
	
	
	public User setAviability(Object... params) {
		StringBuilder builder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		//List<Oficina>  offices =new ArrayList() ;
		
		String url = (String)params[0];
		boolean availability = (Boolean)params[1];
		int userId = (Integer)params[2];
		String message = (String)params[3];
		
		ArrayList<NameValuePair> postParameters;
		
		postParameters = new ArrayList<NameValuePair>();
	    postParameters.add(new BasicNameValuePair("estado", String.valueOf(availability)));
	    postParameters.add(new BasicNameValuePair("userId", String.valueOf(userId)));
	    postParameters.add(new BasicNameValuePair("message", message));
		
		
	    HttpPost httpPost = new HttpPost(url);
	    try {
			httpPost.setEntity(new UrlEncodedFormEntity(postParameters));
		} catch (UnsupportedEncodingException e2) {
			e2.printStackTrace();
		}
		
				
//		HttpPost httpPost =  new HttpPost(url+"?"+"estado="+availability+"&"+"userId="+userId);
		HttpResponse response = null;
		try {
			response = client.execute(httpPost);
		} catch (ClientProtocolException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		StatusLine statusLine = response.getStatusLine();
		int statusCode = statusLine.getStatusCode();
		
		if (statusCode == 200) { //result OK
			HttpEntity entity = response.getEntity();
			InputStream content = null;
			try {
				content = entity.getContent();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(content));
		
		String line;
		try {
			while ((line = reader.readLine()) != null) {
				builder.append(line);
			}
		} catch (IOException e) {
				e.printStackTrace();
			}
		} 
		else { //result BAD
		System.err.println("Failed to download file");
		}
		
		User user =null;
		try {
			ObjectMapper mapper = new ObjectMapper();
			user = mapper.readValue(builder.toString(), User.class);
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return user;
		}

	
	public  Boolean setNotification(Object... params) {
		StringBuilder builder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();

		String url = (String) params[0];
		int funcId = (Integer) params[1];
		int userId = (Integer) params[2];
		int officeId = (Integer) params[3];
		String userName = (String) params[4];
		String message = (String) params[5];
		
		ArrayList<NameValuePair> postParameters;
		
		postParameters = new ArrayList<NameValuePair>();
	    postParameters.add(new BasicNameValuePair("funcID", String.valueOf(funcId)));
	    postParameters.add(new BasicNameValuePair("userId", String.valueOf(userId)));
	    postParameters.add(new BasicNameValuePair("officeId", String.valueOf(officeId)));
	    postParameters.add(new BasicNameValuePair("userName", String.valueOf(userName)));
	    postParameters.add(new BasicNameValuePair("message", message));
		
		
	    HttpPost httpPost = new HttpPost(url);
	    try {
			httpPost.setEntity(new UrlEncodedFormEntity(postParameters));
		} catch (UnsupportedEncodingException e2) {
			e2.printStackTrace();
		}
	    
//		HttpPost httpPost = new HttpPost(url + "?" + "funcID=" + funcId + "&"
//				+ "userId=" + userId + "&" + "officeId=" + officeId + "&" + "userName=" + userName + "&" + "message=" + message);
		
		
		
//		HttpPost httpPost = new HttpPost(url + "?" + "funcID=" + funcId + "&"
//				+ "userId=" + userId + "&" + "userName=" + userName + "&" + "message=" + message);
		HttpResponse response = null;
		try {
			response = client.execute(httpPost);
		} catch (IOException e1) {
			e1.printStackTrace();
			return false;
		}
		StatusLine statusLine = response.getStatusLine();
		int statusCode = statusLine.getStatusCode();

		if (statusCode == 200) { // result OK
			HttpEntity entity = response.getEntity();
			InputStream content = null;
			try {
				content = entity.getContent();
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					content));

			String line;
			try {
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
		} else { // result BAD
			System.err.println("Failed to retrieve info");
		}

		User user = null;
		String jsonFeed = builder.toString();

		// user = mapper.readValue(builder.toString(), User.class);
		return true;
		}
	
	public  ArrayList<Notificacion> getNotification(Object... params) {
		StringBuilder builder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		ArrayList<Notificacion> notificaciones = new  ArrayList<Notificacion>();

		String url = (String) params[0];
		int funcId = (Integer) params[1];
		int officeId = (Integer) params[2];

		HttpPost httpPost = new HttpPost(url + "?" + "funcID=" + funcId + "&"
				+ "officeId=" + officeId);
		HttpResponse response = null;
		try {
			response = client.execute(httpPost);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		StatusLine statusLine = response.getStatusLine();
		int statusCode = statusLine.getStatusCode();

		if (statusCode == 200) { // result OK
			HttpEntity entity = response.getEntity();
			InputStream content = null;
			try {
				content = entity.getContent();
			} catch (IOException e) {
				e.printStackTrace();
			}

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					content));

			String line;
			try {
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else { // result BAD
			System.err.println("Failed to retrieve info");
		}
		String jsonFeed = builder.toString();

		ObjectMapper mapper = new ObjectMapper();
		try {
			notificaciones= mapper.readValue(builder.toString(), new TypeReference<List<Notificacion>>() {});
		} catch (JsonParseException e) {
		} catch (JsonMappingException e) {
		} catch (IOException e) {
			e.printStackTrace();
		}

		
		// user = mapper.readValue(builder.toString(), User.class);
		return notificaciones;
		}

	public User getLoguedUser(Object... params) {
		StringBuilder builder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		User loguedUser = new User();

		String url = (String) params[0];
		String user = (String) params[1];
		String pass = (String) params[2];

		HttpPost httpPost = new HttpPost(url + "?" + "user=" + user + "&"
				+ "pass=" + pass);
		HttpResponse response = null;
		try {
			response = client.execute(httpPost);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		StatusLine statusLine = response.getStatusLine();
		int statusCode = statusLine.getStatusCode();

		if (statusCode == 200) { // result OK
			HttpEntity entity = response.getEntity();
			InputStream content = null;
			try {
				content = entity.getContent();
			} catch (IOException e) {
				e.printStackTrace();
			}

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					content));

			String line;
			try {
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else { // result BAD
			System.err.println("Failed to retrieve info");
		}
		ObjectMapper mapper = new ObjectMapper();
		try {
			loguedUser = mapper.readValue(builder.toString(), User.class);
		} catch (JsonParseException e) {
			e.printStackTrace();
			return loguedUser ;
		} catch (JsonMappingException e) {
			e.printStackTrace();
			return loguedUser ;
		} catch (IOException e) {
			e.printStackTrace();
			return null ;
		}

		return loguedUser;
	}
	
	
	
	
	@Override
	protected Object doInBackground(Object... params) {
		// TODO Auto-generated method stub
		return null;
	}




	
	
	
	
}
